package wang.aweb.childcar.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import wang.aweb.childcar.exception.CarException;
import wang.aweb.childcar.exception.CarExceptionEnum;
import wang.aweb.childcar.filter.UserFilter;
import wang.aweb.childcar.model.dao.MemberMapper;
import wang.aweb.childcar.model.pojo.Device;
import wang.aweb.childcar.model.pojo.Member;
import wang.aweb.childcar.model.pojo.Order;
import wang.aweb.childcar.model.pojo.System;
import wang.aweb.childcar.model.query.MemberParam;
import wang.aweb.childcar.model.req.AvatarNicknameReq;
import wang.aweb.childcar.model.vo.MemberVO;
import wang.aweb.childcar.service.*;
import wang.aweb.childcar.util.MonthDataUtils;
import wang.aweb.childcar.util.StrUtils;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MemberMoneyLogService memberMoneyLogService;
    @Autowired
    private SystemInfoService systemInfoService;
    @Autowired
    private DonateService donateService;
    /**
     * 通过openid获取用户ID
     * @param openid 微信小程序的openid
     * @return
     */
    @Override
    public Integer doLogin(String openid,String inviteCode){

        Member member=memberMapper.selectByOpenId(openid);
        if(member==null){
            //执行注册
            Member regMember=new Member();
            regMember.setOpenid(openid);
            regMember.setCreateTime(new Date());
            regMember.setMoney(0);
            regMember.setUseMoney(0);
            regMember.setStatus(1);
            try {
                regMember.setInviteCode(StrUtils.getInviteCode());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            memberMapper.insert(regMember);
            //判断是否需要赠送
            if(StringUtils.isEmpty(inviteCode)){
                Map info=systemInfoService.getInfo();
                if((Integer) info.get("donate_enable")==1){

                    MemberVO cuser=this.selectByInviteCode(inviteCode);
                    if(cuser!=null){
                        //需要赠送
                        donate(cuser.getId(),(Integer)info.get("donate_enable"));
                    }
                }
            }
            return regMember.getId();
        }else{
            return member.getId();
        }
    }

    private void donate(Integer id,Integer addMoney){
        Member currentMember=selectById(id);
        currentMember.setMoney(currentMember.getMoney()+addMoney);
        int count=memberMapper.updateByPrimaryKeySelective(currentMember);
        memberMoneyLogService.add(currentMember.getId(),(int)addMoney,4,currentMember.getMoney()+addMoney);
        donateService.add(id,addMoney);
        if(count==0){
            throw new CarException(CarExceptionEnum.UPDATE_FAILED);
        }
    }
    @Override
    public MemberVO selectByInviteCode(String inviteCode) {
        Member user=memberMapper.selectByInviteCode(inviteCode);
        return memberToMemberVO(user);
    }
    @Override
    public MemberVO selectByNickname(String nickname){
        Member user=memberMapper.selectByNickname(nickname);
        return memberToMemberVO(user);
    }
    @Override
    public Integer getUserCount(){
        Map<String,Date> query=new HashMap<>();
        query.put("startTime",null);
        query.put("endTime",null);
        Integer count=memberMapper.getCount(query);
        return count;
    }



    @Override
    public Integer getAgentUserCount(Integer agentId,Date starttime,Date endtime){
        Integer count=memberMapper.getAgentUserCount(agentId,starttime,endtime);
        return count;
    }
    @Override
    public Integer getUserDayCount(){
        Map<String,Date> query=new HashMap<>();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        String date=sdf.format(new Date());
        query.put("startTime", MonthDataUtils.getDayStart(date));
        query.put("endTime",MonthDataUtils.getDayEnd(date));
        Integer count=memberMapper.getCount(query);
        return count;
    }
    @Override
    public Member selectById(Integer userId){
        Member user=memberMapper.selectByPrimaryKey(userId);
        return user;
    }
    @Override
    public MemberVO selectVOById(Integer userId){
        Member user=memberMapper.selectByPrimaryKey(userId);
        return memberToMemberVO(user);
    }
    @Override
    public void updateAgentId(Integer id, Integer agentId){
        Member member=new Member();
        member.setId(id);
        member.setAgentId(agentId);
        memberMapper.updateByPrimaryKeySelective(member);
    }
    @Override
    public void updateInfo(AvatarNicknameReq avatarNicknameReq){
        Member currentMember=this.selectById(UserFilter.memberThreadLocal.get().getId());
        currentMember.setAvatar(avatarNicknameReq.getAvatar());
        currentMember.setNickname(avatarNicknameReq.getNickname());
        memberMapper.updateByPrimaryKeySelective(currentMember);
    }
    @Override
    public void consum(Integer id, Integer price){
        memberMapper.consum(id,price);
        //更新操作
        Member afterMember=memberMapper.selectByPrimaryKey(id);
        Integer endMoney=afterMember.getMoney();
        //写日志
        memberMoneyLogService.add(afterMember.getId(),price,2,endMoney);
    }
    @Override
    public void chongzhi(Integer addMoney, Integer memberId) {
        memberMapper.chongzhi(memberId,addMoney);
        Member afterMember=memberMapper.selectByPrimaryKey(memberId);
        Integer endMoney=afterMember.getMoney();
        //写日志
        memberMoneyLogService.add(afterMember.getId(),addMoney,1,endMoney);
    }

    @Override
    public Map checkIsReady() {
        Map<String,Object> resMap=new HashMap<>();
        Order order=orderService.findNoDoneByMemberId(UserFilter.memberThreadLocal.get().getId());
        if(order==null){
            resMap.put("status",0);
        }else{
            resMap.put("status",1);
            resMap.put("orderNo",order.getOrderNo());
            Device device=deviceService.findById(order.getDeviceId());
            resMap.put("imei",device.getImei());
        }
        return resMap;

    }

    @Override
    public void setPhone(String phone) {
        Member member=new Member();
        member.setMobilePhone(phone);
        member.setId(UserFilter.memberThreadLocal.get().getId());
        memberMapper.updateByPrimaryKeySelective(member);
    }
    @Override
    public PageInfo selectList(Integer page,Integer limit,MemberParam memberParam){
        PageHelper.startPage(page,limit);
        List<Member> memberList=memberMapper.selectList(memberParam);
        List<MemberVO> memberVOList=memberListToMemberVOList(memberList);
        PageInfo memberPageInfo=new PageInfo<>(memberList);
        memberPageInfo.setList(memberVOList);
        return memberPageInfo;
    }
    @Override
    public void sysAddMoney(Integer id,Integer addMoney){
        Member currentMember=selectById(id);
        currentMember.setMoney(currentMember.getMoney()+addMoney*100);
        int count=memberMapper.updateByPrimaryKeySelective(currentMember);
        memberMoneyLogService.add(currentMember.getId(),(int)addMoney*100,3,currentMember.getMoney()+addMoney*100);
        if(count==0){
            throw new CarException(CarExceptionEnum.UPDATE_FAILED);
        }
    }
    @Override
    public void disableOrEnable(Integer id){
        Member currentMember=selectById(id);
        if(currentMember.getStatus()==1){
            currentMember.setStatus(0);
        }else{
            currentMember.setStatus(1);
        }
        int count=memberMapper.updateByPrimaryKeySelective(currentMember);
        if(count==0){
            throw new CarException(CarExceptionEnum.UPDATE_FAILED);
        }
    }
    private List<MemberVO> memberListToMemberVOList(List<Member> memberList){
        List<MemberVO> memberVOList=new ArrayList<>();
        for (int i = 0; i < memberList.size(); i++) {
            Member member =  memberList.get(i);
            memberVOList.add(memberToMemberVO(member));
        }
        return memberVOList;
    }
    @Override
    public MemberVO selectByMoblile(String mobile){
        Member currentMember=memberMapper.selectByMobile(mobile);
        return memberToMemberVO(currentMember);
    }
    private MemberVO memberToMemberVO(Member member){
        if(member==null){
            return null;
        }else{
            MemberVO memberVO=new MemberVO();
            BeanUtils.copyProperties(member,memberVO);
            memberVO.setAgent_id(member.getAgentId());
            memberVO.setCreate_time(member.getCreateTime());
            memberVO.setUse_money(member.getUseMoney()/100);
            memberVO.setMobile_phone(member.getMobilePhone());
            memberVO.setMoney(member.getMoney()/100);
            memberVO.setInvite_code(member.getInviteCode());
            return memberVO;
        }

    }
}
